package com.gmail.avereshchaga.db.dao;

import com.gmail.avereshchaga.db.entity.IUserSessionId;
import com.gmail.avereshchaga.db.entity.UserSessionIdImpl;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 *
 * @author <a href="mailto:avereshchaga@gmail.com">Vereshchaga Alexey</a>
 */
@Repository
public class UserSessionIdDAOImpl implements IUserSessionIdDAO {

    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public void createUserSessionId(IUserSessionId userSessionId) {
        sessionFactory.getCurrentSession().save(userSessionId);
    }

    @Override
    public IUserSessionId findBySessionId(Long sessionId) {
        Session session = sessionFactory.getCurrentSession();
        Criteria crit = session.createCriteria(UserSessionIdImpl.class);
        crit.add(Restrictions.eq("sessionId", sessionId));
        IUserSessionId userSessionId = (IUserSessionId) crit.uniqueResult();
        return userSessionId;
    }

    @Override
    public void closeSession(String username, String password) {
        Session session = sessionFactory.getCurrentSession();
        Query q = session
                .createQuery("from UserSessionIdImpl us where us.user.username = :username "
                + "and us.user.password = :password");
        q.setString("username", username);
        q.setString("password", password);
        List<IUserSessionId> sessions = q.list();
        for (IUserSessionId userSessionId : sessions) {
            session.delete(userSessionId);
        }
    }
}
